import useLocale from '@/utils/useLocale';
import React, { useEffect, useState } from 'react';
import moment from 'moment/moment';
import instance from '@/utils/request';
import {
  Badge,
  Card, Empty,
  Grid, PaginationProps, Skeleton,
  Table, Tooltip, Typography
} from '@arco-design/web-react';
import { formatMillisecondsToTime } from '@/utils/time';
import { resolveAlarmLevel, resolveAlarmObject, resolveContinuingName } from '@/constants/functions';
import { defaultPaginationProps } from '@/constants/defaults';
import { AlarmRecordResponse, DeviceResponse } from '@/constants/type';
import { Chart, Interval, Legend, Line, Tooltip as ChartTooltip } from 'bizcharts';
import { chartColors } from '@/constants/constants';

const { Row, Col } = Grid;

const locale = {
  'en-US': {},
  'zh-CN': {
    'columns.id': 'ID',
    'columns.name': '报警名称',
    'columns.code': '报警编码',
    'columns.level': '报警级别',
    'columns.alarm_object': '报警对象',
    'columns.device.name': '设备名称',
    'columns.device.code': '设备编码',
    'columns.time': '发生时间',
    'columns.startTime': '开始时间',
    'columns.endTime': '结束时间',
    'columns.duration': '持续时间',
    'columns.continuing': '报警中',
    'columns.operation': '操作'
  }
};

const AlarmRecordPanel = (props: {
  id: number
}) => {
  const t = useLocale(locale);
  const [loading, setLoading] = useState<boolean>(false);
  const [loadingHistory, setLoadingHistory] = useState<boolean>(false);
  const [data, setData] = useState([]);
  const [history, setHistory] = useState([]);
  const [pagination, setPagination] = useState<PaginationProps>(defaultPaginationProps);

  function fetchData() {
    const date = moment();
    setLoading(true);
    const { current, pageSize } = pagination;
    instance
      .post('/api/alarm/record/page', {
        pager: {
          pageNumber: current,
          pageSize
        },
        sort: [{
          direction: 'desc',
          property: 'startTime'
        }, {
          direction: 'asc',
          property: 'alarmConfigId'
        }],
        query: {
          deviceId: props.id,
          startDateTime: date.format('YYYY-MM-DD') + ' 00:00:00',
          endDateTime: date.format('YYYY-MM-DD') + ' 23:59:59'
        }
      })
      .then((res) => {
        if (res.data.code === 200) {
          setData(res.data.data);
          setPagination({
            ...pagination,
            current,
            pageSize,
            total: res.data.total
          });
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }

  function onChangeTable({ current, pageSize }) {
    setPagination({
      ...pagination,
      current,
      pageSize
    });
  }

  useEffect(() => {
    const fetchHistory = () => {
      setLoadingHistory(true);
      instance
        .post('/api/alarm/analysis/list', {
          query: {
            deviceId: props.id,
            recordDateStart: moment().add(-7, 'day').format('YYYY-MM-DD'),
            recordDateEnd: moment().format('YYYY-MM-DD')
          },
          sort: [
            {
              property: 'recordDate',
              direction: 'asc'
            }
          ]
        })
        .then((res) => {
          if (res.data.code === 200) {
            const r1 = [];
            (res.data.data || []).forEach(it => {
              r1.push({
                recordDate: it.recordDate,
                count: it.count,
                duration: it.duration,
                type: it.alarmConfig?.name
              });
            });
            setHistory(r1);
          }
        })
        .finally(() => {
          setLoadingHistory(false);
        });
    };
    if (!!props.id) {
      fetchData();
      fetchHistory();
    }
  }, [props.id, pagination.current, pagination.pageSize]);

  return (
    <Row>
      <Col span={24}>
        <Card>
          <Row>
            <Col span={24}>
              {!!loadingHistory ? (
                <Skeleton animation />
              ) : (
                (data || []).length === 0 ? (
                  <Empty />
                ) : (
                  <>
                    <Typography.Title heading={6}>
                      {t['title.oee.history']}
                    </Typography.Title>
                    <Row>
                      <Col span={24}>
                        <Chart padding={[10, 90, 20, 90]} autoFit height={200} data={history}>
                          <Legend position={'top'} />
                          <Line position="recordDate*duration" color={['type', chartColors]} />
                          <Interval size={24} position={'recordDate*count'} color={['type', chartColors]} />
                          <ChartTooltip shared />
                        </Chart>
                      </Col>
                    </Row>
                  </>
                )
              )}
            </Col>
          </Row>
        </Card>
      </Col>
      <Col span={24}>
        <Card>
          <Row>
            <Col span={24}>
              <Table style={{ marginTop: '1rem' }} rowKey={record => record.id} loading={loading}
                     onChange={onChangeTable}
                     pagination={pagination} columns={[
                {
                  title: t['columns.id'],
                  dataIndex: 'id',
                  render: (value: number) => <Typography.Text copyable>{value}</Typography.Text>
                },
                {
                  title: t['columns.name'],
                  dataIndex: 'alarmConfig.name'
                },
                {
                  title: t['columns.device.name'],
                  dataIndex: 'device',
                  render: (value: DeviceResponse) => <Tooltip content={value.code}>{value.name}</Tooltip>
                },
                {
                  title: t['columns.level'],
                  dataIndex: 'alarmConfig.level',
                  render: (value: string) => <Typography.Text>{resolveAlarmLevel(value)}</Typography.Text>
                },
                {
                  title: t['columns.alarm_object'],
                  dataIndex: 'alarmConfig.alarmObject',
                  render: (value: string) => <Typography.Text>{resolveAlarmObject(value)}</Typography.Text>
                },
                {
                  title: t['columns.time'],
                  dataIndex: 'startTime',
                  render: (_: string, record: AlarmRecordResponse) => record.startTime + ' - ' + record.endTime
                },
                {
                  title: t['columns.duration'],
                  dataIndex: 'duration',
                  render: (value: number) => formatMillisecondsToTime(value)
                },
                {
                  title: t['columns.continuing'],
                  dataIndex: 'continuing',
                  render: (value: boolean) => {
                    return value === true
                      ? <Badge status="processing" text={resolveContinuingName(value)}></Badge>
                      : <Badge status="success" text={resolveContinuingName(value)}></Badge>;
                  }
                }
              ]} data={data} />
            </Col>
          </Row>
        </Card>
      </Col>
    </Row>
  );
};

export default AlarmRecordPanel;